﻿using System.IO;
using System.Net;
using UnityEngine;
using UnityEngine.Networking;

public delegate void AssetDownloadProgressHandler(float progress);
public delegate void AssetDownloadCompleteHandler();

public class AssetLoader : MonoBehaviour
{
    private string _remoteFileURL;
    public string RemoteURL
    {
        get
        {
            return _remoteFileURL;
        }
    }
    private string _localFileURL;

    private string _tempFileURL;
    [SerializeField]
    private int _bytesTotal = 0;
    [SerializeField]
    private int _bytesLoaded = 0;
    //已下载
    private int _oldBytesLoaded = 0;

    private UnityWebRequest _request=null;
    public bool _finished = false;
    private AssetType _assetType;

    private AssetHandler _downloadHandler;
    public event AssetDownloadProgressHandler ProgressHandler = null;
    public event AssetDownloadCompleteHandler CompleteHandler=null;
    
    public int BytesLoaded
    {
        get
        {
            return _bytesLoaded;
        }
    }

    public int BytesTotal
    {
        get
        {
            return _bytesTotal;
        }
    }

    public float Progress
    {
        get
        {
            return (float)_bytesLoaded / _bytesTotal;
        }
    }

    
    public static AssetLoader Create(string remoteFile,AssetType type= AssetType.Other)
    {
        GameObject go = new GameObject("[AssetLoader]-"+Path.GetFileName(remoteFile));
        AssetLoader loader = go.AddComponent<AssetLoader>();
        loader._assetType = type;
        loader._remoteFileURL = remoteFile;
        //根据平台选择路径
        if (Application.platform == RuntimePlatform.WindowsEditor)
        {
            //组合本地存储路径
            loader._localFileURL = AssetManager.CacheDir + @"\" + type.ToString().ToLower() + @"\" + Path.GetFileName(remoteFile);
            //组合临时路径
            loader._tempFileURL = AssetManager.CacheDir + @"\" + type.ToString().ToLower() + @"\" + Path.GetFileNameWithoutExtension(remoteFile) + ".tmp";
        }
        else
        {
            //组合本地存储路径
            loader._localFileURL = AssetManager.CacheDir + "/" + type.ToString().ToLower() + "/" + Path.GetFileName(remoteFile);
            //组合临时路径
            loader._tempFileURL = AssetManager.CacheDir + "/" + type.ToString().ToLower() + "/" + Path.GetFileNameWithoutExtension(remoteFile) + ".tmp";
        }
        loader.transform.SetParent(AssetManager.Instance.transform);
        return loader;
    }

    public void Download(string remoteFile,AssetType type= AssetType.Other)
    {
        //获得要下载文件的大小信息
        HttpWebRequest tmprequest = (HttpWebRequest)WebRequest.Create(remoteFile);
        HttpWebResponse tmpresponse = (HttpWebResponse)tmprequest.GetResponse();
        _bytesTotal = (int)tmpresponse.ContentLength;
        tmprequest.Abort();
        tmpresponse.Close();
        Debug.Log("[AssetLoader]远程路径:" + _remoteFileURL);
        Debug.Log("[AssetLoader]本地路径:" + _localFileURL);
        Debug.Log("[AssetLoader]临时文件:" + _tempFileURL);

        Debug.Log("[AssetLoader]需要下载的文件大小:" + AssetManager.FormatBytes(_bytesTotal));

        //检测本地是否存在此文件
        if (File.Exists(_localFileURL))
        {
            _bytesLoaded = _bytesTotal;
            Debug.Log("[AssetLoader]此文件已经下载过，取消重复下载" + AssetManager.FormatBytes(_bytesLoaded)+"/"+AssetManager.FormatBytes(_bytesTotal));
            return;
        }

        //创建下载监听器
        _downloadHandler = new AssetHandler(_remoteFileURL, _tempFileURL);
        
        _request = UnityWebRequest.Get(_remoteFileURL);
        _request.chunkedTransfer = true;
        _request.disposeDownloadHandlerOnDispose = true;
        _request.SetRequestHeader("Range", "bytes=" + _downloadHandler.BytesLoaded + "-"); //断点续传设置读取文件数据流开始索引，成功会返回206
        _request.downloadHandler = _downloadHandler;
        _request.SendWebRequest();
    }
 
    public void Update()
    {
        if (_downloadHandler != null)
        {
            _bytesLoaded = _downloadHandler.BytesLoaded;
        }
        if (_oldBytesLoaded != _bytesLoaded)
        {
            _oldBytesLoaded = _bytesLoaded;

            if (ProgressHandler != null)
            {
                ProgressHandler(_bytesLoaded / _bytesTotal);
            }
        }
        if (!_finished && _bytesLoaded == _bytesTotal)
        {
            _finished = true;
            Debug.Log("下载结束 " + _bytesLoaded);
            if (_downloadHandler != null)
            {
                _downloadHandler.OnDispose();
                //重命名
                FileInfo fi = new FileInfo(_tempFileURL);
                fi.MoveTo(_localFileURL);
            }

            if (CompleteHandler != null)
            {
                CompleteHandler();
            }
            Destroy(this.gameObject);
         }
 
     }

    public void OnDestroy()
    {
        if (_request != null)
        {
            _request.Abort();
            _request.Dispose();
            _request = null;
        }
 

    }

    public override string ToString()
    {
        string info = "[" + _assetType + "]" + _remoteFileURL;
        return info;
    }

}
